package com.yubest.security.filter;

import cn.hutool.extra.spring.SpringUtil;
import com.yubest.security.bean.UserInfo;
import com.yubest.security.consts.Consts;
import com.yubest.security.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class VerifyFilter extends BasicAuthenticationFilter {

    public VerifyFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        TokenService tokenService = SpringUtil.getBean(TokenService.class);
        String token = tokenService.getCurrentToken();
        if (token == null) {
            chain.doFilter(request, response);
            return;
        }
        UserInfo userInfo = tokenService.get(token);
        if (userInfo != null) {
            Authentication authResult = new UsernamePasswordAuthenticationToken
                    (userInfo.getUsername(), null, userInfo.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authResult);
        }
        chain.doFilter(request, response);
    }

}